﻿using RuoVea.Entity;
using Mapster;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using RuoVea.Autowired;
using RuoVea.ExSqlSugar;

using RuoVea.ExIdGen;
using System;
using RuoVea.ExEnum;
using RuoVea.Util;

namespace RuoVea.Service
{
    /// <summary>
    /// 访问日志服务
    /// </summary>
    [AppService(ServiceLifetime.Transient)]
    public class SysVisLogService : ISysVisLogService 
    {
        private readonly ISqlSugarRepository<SysLogVis> _sysVisLogRep;  // 访问日志表仓储

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sysVisLogRep"></param>
        public SysVisLogService(ISqlSugarRepository<SysLogVis> sysVisLogRep)
        {
            _sysVisLogRep = sysVisLogRep;
        }

        /// <summary>
        /// 分页查询访问日志
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<dynamic> QueryVisLogPageList(VisLogInput input)
        {
           var visLogs = await _sysVisLogRep.Context.Queryable<SysLogVis>()
                                             .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name))
                                             .WhereIF(input.VisType > 0, u => u.VisType == input.VisType)
                                             .WhereIF(Enum.IsDefined(typeof(YesOrNot), input.Success), u => u.Success == input.Success)
                                             .WhereIF(!string.IsNullOrWhiteSpace(input.SearchBeginTime), u => u.VisTime >= DateTime.Parse(input.SearchBeginTime.Trim()) && u.VisTime <= DateTime.Parse(input.SearchEndTime.Trim()))
                                             .OrderBy(u => u.Id, OrderByType.Desc)
                                             .Select<VisLogOutput>()
                                             .ToPagedListAsync(input.PageNo, input.PageSize);
            return visLogs.XnPagedResult();
        }

        /// <summary>
        /// 清空访问日志
        /// </summary>
        /// <returns></returns>
        public async Task ClearVisLog()
        {
            await _sysVisLogRep.DeleteAsync(m => true);
        }
    }
}
